<template>
    <div>
      <!-- 当天进出库总额度 -->
      <el-card>
        <h3>当天进出库总额度</h3>
        <p>入库总额度：{{ dailySummary.totalStockInAmount }}</p>
        <p>出库总额度：{{ dailySummary.totalStockOutAmount }}</p>
      </el-card>
  
      <!-- 入库和出库按钮 -->
      <el-button type="primary" @click="showBatchForm('入库')">入库</el-button>
      <el-button type="danger" @click="showBatchForm('出库')">出库</el-button>
  
      <!-- 搜索框 -->
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="8">
          <el-input v-model="searchQuery.id" placeholder="输入库存ID" />
        </el-col>
        <el-col :span="8">
          <el-date-picker v-model="searchQuery.startDate" type="date" placeholder="开始日期" />
        </el-col>
        <el-col :span="8">
          <el-date-picker v-model="searchQuery.endDate" type="date" placeholder="结束日期" />
        </el-col>
        <el-col :span="8">
          <el-button type="primary" @click="searchStock">搜索</el-button>
        </el-col>
      </el-row>
  
      <!-- 库存列表 -->
      <div>
    <!-- 选项卡 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="入库记录表" name="stock-in"></el-tab-pane>
      <el-tab-pane label="出库记录表" name="stock-out"></el-tab-pane>
    </el-tabs>

    <!-- 数据表格 -->
    <el-table :data="records" style="margin-top: 20px;" border>
      <el-table-column prop="detailID" label="明细 ID" width="100"></el-table-column>
      <el-table-column prop="productName" label="商品名称" width="150"></el-table-column>
      <el-table-column prop="warehouseName" label="仓库名称" width="150"></el-table-column>
      <el-table-column prop="quantity" label="数量" width="100"></el-table-column>
      <el-table-column prop="purchasePrice" label="价格" width="100">
        <template #default="scope">
          ￥{{ scope.row.purchasePrice.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="orderDate" label="日期" width="180">
        <template #default="scope">
          {{ new Date(scope.row.orderDate).toLocaleString() }}
        </template>
      </el-table-column>
      <el-table-column prop="processedBy" label="操作人" width="120"></el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @current-change="fetchRecords"
      :current-page="currentPage"
      :page-size="pageSize"
      :total="totalRecords"
      layout="prev, pager, next"
      style="margin-top: 20px;"
    />
  </div>
  
      <!-- 统计按钮 -->
      <el-button type="success" @click="calculateProfit" style="margin-top: 20px;">统计总利润</el-button>
  
      <!-- 批量入库/出库表单 -->
      <el-dialog :title="batchType + '操作'" v-model="showBatchDialog">
        <el-form ref="batchForm" :model="batchForm" label-width="120px">
          <el-form-item label="操作时间"><S></S>
            <el-date-picker v-model="batchForm.operationDate" type="datetime" placeholder="选择操作时间" />
          </el-form-item>
          <el-form-item label="操作人">
            <el-select v-model="batchForm.operator" placeholder="选择操作人">
              <el-option v-for="user in operators" :key="user.id" :label="user.name" :value="user.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="商品数据">
            <el-table :data="batchForm.items" border>
              <el-table-column prop="productName" label="商品名称">
                <template #default="scope">
                  <el-autocomplete
                    v-model="scope.row.productName"
                    :fetch-suggestions="fetchProductSuggestions"
                    placeholder="输入商品名称"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="warehouseId" label="仓库ID">
                <template #default="scope">
                  <el-input v-model="scope.row.warehouseId" />
                </template>
              </el-table-column>
              <el-table-column prop="price" label="单价">
                <template #default="scope">
                  <el-input v-model="scope.row.price" />
                </template>
              </el-table-column>
              <el-table-column prop="quantity" label="数量">
                <template #default="scope">
                  <el-input v-model="scope.row.quantity" />
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button type="danger" @click="removeItem(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button type="primary" @click="addItem">添加一行</el-button>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="showBatchDialog = false">取消</el-button>
          <el-button type="primary" @click="submitBatchForm">确认</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { useProductStore } from '../stores/productStore';
  import axios from 'axios';
  
  export default {
    data() {
      return {
        dailySummary: {
          totalStockInAmount: 0,
          totalStockOutAmount: 0,
        },
        activeTab: "stock-in", // 当前选中的选项卡
      records: [], // 数据表格中的记录
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示的记录数
      totalRecords: 0, // 总记录数
        searchQuery: {
          id: '',
          startDate: '',
          endDate: '',
        },
        showBatchDialog: false,
        batchType: '',
        batchForm: {
          operationDate: '',
          operator: '',
          items: [],
        },
        operators: [
          { id: 1, name: '操作人1' },
          { id: 2, name: '操作人2' },
        ],
      };
    },
    methods: {
      handleTabClick() {
    this.currentPage = 1; // 切换选项卡时重置为第一页
    this.fetchRecords(); // 加载对应的记录
  },
      async fetchDailySummary() {
        const response = await axios.get('http://localhost:5123/api/Stock/daily-summary', {
          params: { date: new Date().toISOString().split('T')[0] },
        });
        this.dailySummary = response.data;
      },
      async fetchRecords(page = this.currentPage) {
      try {
        const url =
          this.activeTab === "stock-in"
            ? "http://localhost:5123/api/Stock/stock-in-details"
            : "http://localhost:5123/api/Stock/stock-out-details";

        const response = await axios.get(url, {
          params: {
            page,
            pageSize: this.pageSize,
          },
        });

        console.log("分页返回的数据:", response.data);

        // 更新数据
        this.records = response.data.items; // 假设后端直接返回列表数据
        this.totalRecords = response.data.totalRecords;
      } catch (error) {
        console.error("获取记录失败:", error);
        this.$message.error("获取记录失败，请稍后重试");
      }
    },

      async searchStock() {
        const response = await axios.get('http://localhost:5123/api/Stock/search', {
          params: {
            id: this.searchQuery.id,
            startDate: this.searchQuery.startDate,
            endDate: this.searchQuery.endDate,
          },
        });
        this.stocks = response.data;
      },
      async calculateProfit() {
        const response = await axios.get('http://localhost:5123/api/Stock/profit');
        this.$message.success(`总利润：${response.data.totalProfit}`);
      },
      showBatchForm(type) {
        console.log(`打开${type}表单`);
        this.batchType = type;
        this.showBatchDialog = true;
      },
      addItem() {
        this.batchForm.items.push({
          productName: '',
          warehouseId: '',
          price: '',
          quantity: '',
        });
      },
      removeItem(index) {
        this.batchForm.items.splice(index, 1);
      },
      async submitBatchForm() {
  try {
    // 转换数据格式
    const transformedData = {
      orderDate: this.batchForm.operationDate.toISOString(), // 转换为 ISO 格式的日期字符串
      processedBy: this.batchForm.operator.toString(), // 转换为字符串
      details: this.batchForm.items.map(item => ({
        productID: parseInt(item.productName), // 假设 productName 实际上是 productID
        warehouseID: parseInt(item.warehouseId), // 转换为数字
        quantity: parseInt(item.quantity), // 转换为数字
        purchasePrice: parseFloat(item.price), // 转换为数字
      })),
    };

    console.log('转换后的数据:', transformedData);

    // 提交数据
    const url = 'http://localhost:5123/api/Stock/add-stock-in';
    const response = await axios.post(url, transformedData, {
      headers: {
        'Content-Type': 'application/json',
      },
    });

    console.log('服务器响应:', response.data);
    this.$message.success('入库成功！');
    this.showBatchDialog = false; // 关闭弹窗
    this.fetchStocks(this.currentPage); // 刷新库存列表
  } catch (error) {
    console.error('入库失败:', error);

    if (error.response) {
      this.$message.error(`服务器错误：${error.response.status} - ${error.response.data.message || '未知错误'}`);
    } else if (error.request) {
      this.$message.error('请求失败：服务器未响应');
    } else {
      this.$message.error(`请求失败：${error.message}`);
    }
  }
}
      //async fetchProductSuggestions(queryString, callback) {
       // const response = await axios.get('http://localhost:5123/api/products/search', {
        //  params: { keyword: queryString },
        //});
        //callback(response.data.map((item) => ({ value: item.name, id: item.id })));
     // },
    },
    async mounted() {
      //await this.fetchDailySummary();
      //await this.fetchStocks();
      this.fetchRecords();
    },
  };
  </script>
  